package com.semlab.server.enrichment;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.semlab.server.graph.ConceptRepository;
import com.semlab.server.graph.Neo4jTemplate;
import com.semlab.server.resources.Concept;
import com.semlab.server.resources.SLog;

@Component
public class EnrichConceptsService {

	@Autowired
	ConceptRepository concepts;
	@Autowired
	DBpediaExtractor dbpedia;
	@Autowired
	Neo4jTemplate template;

	public void process() {

		template.beginTransaction();
		// get concept from neo4j
		Concept concept = concepts.getNextConceptToEnrich();
		if (concept != null) {
			do {
				SLog.debug(getClass(), "trying to enrich concept: ", concept);

				enrichConcept(concept);
				concept = concepts.getNextConceptToEnrich();
			} while (concept != null);
			template.finishTransaction();

		} else {
			SLog.debug(getClass(), "No concepts to enrich in queue");
		}

	}

    private void enrichConcept(Concept concept) {
        // ask nemanja for concepts
        Concept dbconcept = dbpedia.enrichConcept(concept);

        if (dbconcept == null) {
            SLog.debug(getClass(), "dbconcept == null", concept);
            concept.changeDateEnriched(false);
            concept.incrementEnrichCounter();
            if (concept.getEnrichCounter() < ConceptRepository.UPDATE_LIMIT) {
                concepts.assignConceptForEnrichment(concept);
            } else {
                concept.setEnriched(true);
            }
            concepts.persist(concept);
        } else {
            SLog.debug(getClass(), "finished enrichment", concept);
            dbconcept.changeDateEnriched(true);
            concepts.persist(dbconcept);
        }
    }

}
